import os
from flask import Flask
from flask import render_template ,Flask,  url_for, redirect, request, jsonify
import json
import time

from jinja2 import Environment,FileSystemLoader


def api_upload(app_boj, file):
    basedir = os.path.abspath(os.path.dirname(__file__))  # 获取当前项目的绝对路径
    file_dir = os.path.join(basedir, app_boj.config['UPLOAD_FOLDER'])  # 拼接成合法文件夹地址
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)  # 文件夹不存在就创建
    fname = file.filename
    ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
    unix_time = int(time.time())
    new_filename = str(unix_time)+'.'+ext   # 修改文件名
    file.save(os.path.join(file_dir, new_filename))  #保存文件到upload目录
    return jsonify({"result": 1, "new_name": new_filename, "errmsg": "上传成功"})

def render(tpl_path, **kwargs):
    path,filename = os.path.split(tpl_path)
    env = Environment(loader=FileSystemLoader(path or './'))
    template = env.get_template(filename)
    return template.render(**kwargs)

TEMPLATE_PATH = 'templates'

def add_templates_dir_path(file_path):
    ret = os.path.join(TEMPLATE_PATH, file_path)
    return ret

app = Flask(__name__, template_folder=TEMPLATE_PATH)
app.config["SECRET_KEY"] = "XXXXDWEFS"

UPLOAD_FOLDER = './templates'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 设置文件上传的目标文件夹

@app.route("/api/upload", methods=["GET", "POST"])
def upload():
    file = request.files.get("file_data")
    msg = api_upload(app, file)
    upload_msg = json.loads(msg.data.decode("utf-8"))
    errmsg = upload_msg.get("errmsg")
    return jsonify({"msg": errmsg})


@app.route('/')
def show_test():
    return render_template("show.html")

# def test_simple():
#     title = "测试jinjia2模板 "
#     items = [{'href':'https://www.baidu.com/','caption':'百度'},{'href':'test.www.com','caption':'个人博客'}]
#     content = "网站跳转链接如下："
#     # return render_template(add_templates_dir_path('simple.html'),title=title,items=items,content=content)
#     context = {
#         'title': title,
#         'items': items,
#         'content': content
#     }
#     # return render(os.path.abspath('templates/simple.html'), title=title, items=items, content=content)
#     # return render(os.path.abspath('templates/simple.html'), **context)
#     # return render(os.path.abspath('templates/simple1.txt'), **context)
#     # return redirect('http://127.0.0.1:5000/pdfjs/web/viewer.html?file=../../output.pdf')
#
#     # return render_template(os.path.abspath('templates/pdfjs/web/viewer.html'))
#     return render_template('pdfjs/web/viewer.html')
#
#     # return render_template('simple.html', title=title, items=items, content=content)
#     # return render_template('simple.html')
#     # redirect(url_for('index', username=username))
#     # return render_template('simple.html',title=title,items=items,content=content)


@app.route('/a')
def index():
    return render(os.path.abspath('templates/output.pdf'))
    # return render_template('showPdf.html')
    # return render_template('/pdfjs/web/viewer.html')

from flask import send_file, send_from_directory
import os


# @app.route("/download/<filename>", methods=['GET'])
@app.route("/d", methods=['GET'])
def download_file(filename=''):
    # 需要知道2个参数, 第1个参数是本地目录的path, 第2个参数是文件名(带扩展名)
    # directory = os.getcwd()  # 假设在当前目录
    directory = 'templates'
    filename = 'output.pdf'
    return send_from_directory(directory, filename, as_attachment=True)


if __name__ == "__main__":
    app.run(debug=True)

